#!/usr/bin/env perl

use strict;
use warnings;

our $SRC_DIR = "src/main/java";
our $PKG_DIR = "ca/wilkinsonlab/sadi/service/generator";

[ -d "$SRC_DIR/$PKG_DIR" ] or die "run from project root directory\n";

print <<EOF;

SADI service generator plugin 0.1.0
  The SADI service generator plugin creates the skeleton of a Java servlet
  that works as a SADI service.

This plugin has 2 goals:

EOF

foreach my $file (<$SRC_DIR/$PKG_DIR/*.java>) {
    open FILE, $file
        or die "error reading $file: $!";
    my $mojo = read_javadoc_block(\*FILE);
    print <<EOF;
sadi-generator:$mojo->{"goal"}
  $mojo->{"body"}
EOF
    my @params;
    while (not eof FILE) {
        my $param = read_javadoc_block(\*FILE);
        push @params, $param if ($param->{"parameter"});
    }
    
    if (@params) {
        print <<EOF;
  This goal has the following parameters:
EOF
        foreach my $param (@params) {
            my ($property) = ($param->{"parameter"} =~ /\$\{(\w+)\}/);
            my $body = $param->{"body"};
            format STDOUT =
    @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    $property
      ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
      $body
      ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~
      $body
.
            write;
        }
    } else {
        print <<EOF;
  This goal has no parameters.
EOF
    }
    print "\n";
}

# this is not even remotely general; it might not even work with all of our
# own future comments... just don't assume it's working, ever.
sub read_javadoc_block {
    my ($fh) = @_;

    my $javadoc = { body => "" };
    while (<$fh>) { # find start of next JavaDoc comment...
    	/\/\// && next;
        /\/\*\*/ && last;
    }
    return {} if (eof $fh);
    while (<$fh>) { # read until end of comment...
        /\*\// && last;
        if (/\@(\w+)\s+(.*)/) {
            $javadoc->{$1} = $2;
        } else {
            chomp;
            s/.*\*\s+/ /;
            $javadoc->{"body"} .= $_;
        }
    }
    $javadoc->{"body"} =~ s/^ //;
    return $javadoc;
}
